﻿using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Windows.Forms;
using DevelopTool.Common;
using Sunny.UI;

namespace DevelopTool
{
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        private static void Main(string[] args)
        {
            try
            {
                //只允许打开一个程序，如果已经打开了程序，那么就把已打开的程序显示到前台
                using(Mutex mutex = new Mutex(true,GlobalData.AppName_en,out bool createdNew))
                {
                    if(createdNew || !NotifyBringToFront(args))
                    {
                        //添加事件处理程序未捕获的异常   
                        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                        //添加事件处理UI线程异常   
                        Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
                        //添加事件处理非UI线程异常   
                        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);

                        Application.ApplicationExit += Application_ApplicationExit;

                        //指定 DLL 存放目录
                        WindowsHelper.SetAppDllDirectory(GlobalData.DLLFilePath);

                        bool isAutoStart = args != null && args.Length > 0 && args[0] == "-autostart";
                        Application.Run(new MainForm(isAutoStart,args));
                    }
                }
            }
            catch(Exception ex)
            {
                string str = string.Empty;
                string strDateInfo = DateTime.Now.String() + "\r\n" + "出现应用程序未处理的异常：\r\n";

                if(ex != null)
                {
                    str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                         ex.GetType().Name,ex.Message,ex.StackTrace);
                }
                else
                {
                    str = string.Format("应用程序线程错误:{0}",ex);
                }
                LogHelper.WriteErrLog(str);//写日志
                UIMessageBox.ShowMessageDialog("异常消息：【" + ex.Message + "】\r\t\n详细信息请查看日志文件","系统错误",showCancel: false,UIStyle.Red);
            }
        }


        /// <summary>
        /// 通知程序显示到前台
        /// </summary>
        private static bool NotifyBringToFront(string[] args)
        {
            try
            {
                //创建命名管道客户端
                using(NamedPipeClientStream pipeClient = new NamedPipeClientStream(".",GlobalData.AppName_en,PipeDirection.InOut))
                {
                    // 连接到命名管道（如果已存在的实例正在监听）  
                    pipeClient.Connect(10000);//等待10秒超时

                    // 向命名管道服务器发送消息  
                    using(StreamWriter sw = new StreamWriter(pipeClient))
                    {
                        sw.Write("BringToFront*" + string.Join("|",args));
                        sw.Flush();
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }


        /// <summary>
        /// 程序关闭前事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Application_ApplicationExit(object sender,EventArgs e)
        {
            QuartzHelper.DeleteAllJobs();//删除所有定时任务
        }


        #region 异常处理

        /// <summary>
        /// 程序异常处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Application_ThreadException(object sender,System.Threading.ThreadExceptionEventArgs e)
        {
            string str = string.Empty;
            string strDateInfo = DateTime.Now.String() + "\r\n" + "出现应用程序未处理的异常：\r\n";
            Exception error = e.Exception ?? e.Exception.InnerException;
            if(error != null)
            {
                str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                     error.GetType().Name,error.Message,error.StackTrace);
            }
            else
            {
                str = string.Format("应用程序线程错误:{0}",e);
            }
            LogHelper.WriteErrLog(str); //写日志
            UIMessageBox.ShowMessageDialog("异常消息：【" + error.Message + "】\r\t\n详细信息请查看日志文件","系统错误",showCancel: false,UIStyle.Red);
        }

        /// <summary>
        ///  处理UI异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void CurrentDomain_UnhandledException(object sender,UnhandledExceptionEventArgs e)
        {
            string str = string.Empty;
            Exception error = e.ExceptionObject as Exception;
            string strDateInfo = DateTime.Now.String() + "\r\n" + "出现应用程序未处理的异常：\r\n";
            if(error != null)
            {
                str = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r堆栈信息:{1}",error.Message,error.StackTrace);
            }
            else
            {
                str = string.Format("Application UnhandledError:{0}",e);
            }
            LogHelper.WriteErrLog(str); //写日志
            UIMessageBox.ShowMessageDialog("异常消息：【" + error.Message + "】\r\t\n详细信息请查看日志文件","系统错误",showCancel: false,UIStyle.Red);
        }

        #endregion
    }
}
